#pragma
#include "log.hpp"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <sys/ipc.h>

// 共享内存的大小一般建议是4096的整数倍
// 4097,实际上操作系统给你的是4096*2的大小,但只能使用其中的4097
const int size  = 4096;
const char *pathname = "/home/wangzn2016/11-19";
const int pro_id = 0x6666;

Log log;  // 开启日志

key_t GetKey()
{
    key_t k = ftok(pathname, pro_id);
    if (k < 0) 
    {
        log(Fatal, "ftok error: %s", strerror(errno));
        exit(1);
    }
    log(Info, "ftok success, key is 0x%x", k);
    return k;
}

int GetShareMemHelper(int shmflag)
{
    key_t k = GetKey();
    int shmid = shmget(k, size, shmflag);
    if (shmid < 0) 
    {
        log(Fatal, "shmget to create share memory errno: %s",strerror(errno));
        exit(2);
    }
    log(Info, "shmget to create share memory success, shmid: %d", shmid);
    return shmid;
}

int CreateShm()  // 创建共享内存
{
    return GetShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm()  // 获取共享内存
{
    return GetShareMemHelper(IPC_CREAT);
}

// 借助管道来实现同步异步

#define FIFO_FILE "./myfifo"
#define MODE 0664
#define BUFFERSIZE 1024

enum 
{
    FIFO_CREATE_ERR = 1,
    FIFO_OPEN_ERR,
    FIFO_DELETE_ERR
};

class Init
{
public:

    Init()
    {
        // 创建管道
        int n = mkfifo(FIFO_FILE, MODE);
        if (n == -1) 
        {
            log(Fatal, "mkfifo error: %s, error code: %d", strerror(errno), errno);
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {
        // 删除管道
        int m = unlink(FIFO_FILE);
        if (m == -1)
        {
            log(Error, "unlink error: %s, error code: %d", strerror(errno), errno);
            exit(FIFO_DELETE_ERR);
        }  
    }
};